import { Form, message, Modal } from 'antd';
import { ReactNode, useState } from 'react';
import router from 'next/router';
import IconButton from './iconbutton';
import Button from './button';

export default function EditButton({ children, dlgtitle, onSave }: { children: ReactNode; dlgtitle: string; onSave(): Promise<true | string>; }) {
	const [visible, setvisible] = useState(false);
	const [confirmLoading, setConfirmLoading] = useState(false);
	return <>
		<IconButton img='/images/icons/edit.svg' label='编辑' onClick={() => {
			setvisible(true);
		}} />
		<Modal confirmLoading={confirmLoading} title={dlgtitle || '编辑'} visible={visible} onCancel={() => {
			setConfirmLoading(false);
			setvisible(false);
		}} footer={null} >
			<Form layout='horizontal'>
				{children}
				<div className='footer'>
					<Button value='保存' onClick={async () => {
						try {
							const ok = await onSave();
							if (ok === true) {
								message.success({ content: '保存成功' });
								router.reload();
							} else {
								message.error({ content: ok });
							}
						} catch (error) {
							console.error(error);
						} finally {
							setConfirmLoading(false);
						}
					}} />
				</div>
			</Form>
		</Modal>
		<style jsx>{`
.footer{
	display: flex;
	justify-content: center;
}
`}</style>
	</>;
}
